<template>
  <div>
    <a-card title="酒店评论管理">
      <div class="filter-bar">
        <a-space>
          <a-select
            v-model:value="filterRating"
            style="width: 120px"
            placeholder="评分筛选"
            allow-clear
          >
            <a-select-option :value="5">5星</a-select-option>
            <a-select-option :value="4">4星</a-select-option>
            <a-select-option :value="3">3星</a-select-option>
            <a-select-option :value="2">2星</a-select-option>
            <a-select-option :value="1">1星</a-select-option>
          </a-select>
          
          <a-select
            v-model:value="filterStatus"
            style="width: 120px"
            placeholder="状态筛选"
            allow-clear
          >
            <a-select-option value="replied">已回复</a-select-option>
            <a-select-option value="pending">待回复</a-select-option>
            <a-select-option value="hidden">已隐藏</a-select-option>
          </a-select>
          
          <a-range-picker
            v-model:value="dateRange"
            style="width: 240px"
          />
          
          <a-button type="primary" @click="applyFilter">
            筛选
          </a-button>
          
          <a-button @click="resetFilter">
            重置
          </a-button>
        </a-space>
      </div>
      
      <div class="reviews-list">
        <a-list
          :data-source="reviews"
          item-layout="vertical"
          :loading="loading"
          :pagination="pagination"
        >
          <template #renderItem="{ item }">
            <a-list-item>
              <a-card
                :bordered="false"
                :class="{ 'review-hidden': item.status === 'hidden' }"
              >
                <template #title>
                  <div class="review-header">
                    <div class="review-user">
                      <a-avatar :src="item.userAvatar || getRandomAvatar(item.id)">
                        {{ item.userName?.substring(0, 1) || '用' }}
                      </a-avatar>
                      <span class="user-name">{{ item.userName || '匿名用户' }}</span>
                    </div>
                    <div class="review-meta">
                      <a-rate :value="item.rating" disabled allow-half />
                      <span class="review-date">{{ item.date }}</span>
                    </div>
                  </div>
                </template>
                
                <div class="review-content">
                  <div class="review-text">{{ item.content }}</div>
                  
                  <div class="review-photos" v-if="item.photos && item.photos.length > 0">
                    <a-image
                      v-for="(photo, index) in item.photos"
                      :key="index"
                      :src="photo"
                      :width="80"
                      :height="80"
                      style="margin-right: 8px; margin-bottom: 8px; object-fit: cover;"
                    />
                  </div>
                  
                  <div class="review-tags" v-if="item.tags && item.tags.length > 0">
                    <a-tag v-for="tag in item.tags" :key="tag" color="blue">{{ tag }}</a-tag>
                  </div>
                  
                  <div class="review-reply-section" v-if="item.reply">
                    <div class="reply-header">
                      <message-outlined />
                      <span class="reply-title">酒店回复</span>
                      <span class="reply-date">{{ item.replyDate }}</span>
                    </div>
                    <div class="reply-content">{{ item.reply }}</div>
                    <div class="reply-actions">
                      <a-button 
                        type="link" 
                        size="small"
                        @click="openReplyModal(item)"
                      >
                        编辑回复
                      </a-button>
                    </div>
                  </div>
                  
                  <div class="review-actions" v-if="!item.reply">
                    <a-button 
                      type="primary" 
                      size="middle"
                      @click="openReplyModal(item)"
                    >
                      回复评论
                    </a-button>
                  </div>
                </div>
              </a-card>
            </a-list-item>
          </template>
          <template #empty>
            <a-empty description="暂无评论" />
          </template>
        </a-list>
      </div>
    </a-card>
    
    <!-- 回复模态框 -->
    <a-modal
      v-model:visible="replyModalVisible"
      title="回复评论"
      @ok="submitReply"
      @cancel="replyModalVisible = false"
      :okText="currentReview?.reply ? '更新回复' : '提交回复'"
      cancelText="取消"
    >
      <a-form>
        <a-form-item label="评论内容">
          <div class="review-preview">
            <div class="review-preview-header">
              <span class="user-name">{{ currentReview?.userName }}</span>
              <a-rate :value="currentReview?.rating" disabled allow-half />
            </div>
            <div class="review-preview-content">{{ currentReview?.content }}</div>
          </div>
        </a-form-item>
        
        <a-form-item label="回复内容">
          <a-textarea
            v-model:value="replyContent"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </a-form-item>
      </a-form>
    </a-modal>
    
    <!-- 评论统计 -->
    <a-card title="评论统计" style="margin-top: 16px;">
      <div class="stats-container">
        <div class="stats-overview">
          <div class="stat-item">
            <div class="stat-value">{{ reviewStats.averageRating.toFixed(1) }}</div>
            <div class="stat-label">平均评分</div>
            <a-progress 
              :percent="reviewStats.averageRating * 20" 
              :stroke-color="ratingColor" 
              :show-info="false"
            />
          </div>
          
          <div class="stat-item">
            <div class="stat-value">{{ reviewStats.totalReviews }}</div>
            <div class="stat-label">总评论数</div>
          </div>
          
          <div class="stat-item">
            <div class="stat-value">{{ replyRate.toFixed(0) }}%</div>
            <div class="stat-label">回复率</div>
            <a-progress 
              :percent="replyRate" 
              stroke-color="#1890ff" 
              :show-info="false"
            />
          </div>
        </div>
        
        <a-divider />
        
        <div class="rating-distribution">
          <div class="distribution-title">评分分布</div>
          <div class="distribution-item" v-for="i in 5" :key="i">
            <span class="distribution-label">{{ i }}星</span>
            <a-progress 
              :percent="getRatingDistributionPercent(i)" 
              :stroke-color="getRatingColor(i)"
              :show-info="false"
              style="flex: 1; margin: 0 16px;"
            />
            <span class="distribution-count">{{ getRatingCount(i) }}</span>
          </div>
        </div>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { MessageOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs';
import { 
  apiGetHotelReviews, 
  apiGetHotelReviewStats, 
  apiReplyReview, 
  apiUpdateReviewStatus 
} from '@/api/admin-api';
import { useHotelStore } from '@/stores/hotelStrore';
const hotelStore = useHotelStore(); 

// 定义评论项的接口
interface ReviewItem {
  id: number;
  userName?: string;
  userAvatar?: string;
  rating: number;
  content: string;
  date: string;
  photos?: string[];
  tags?: string[];
  reply?: string;
  replyDate?: string;
  status: 'pending' | 'replied' | 'hidden' | 'deleted';
}

// 定义评论统计信息接口
interface ReviewStats {
  totalReviews: number;
  averageRating: number;
  ratingDistribution: {
    [key: string]: number;
  };
}

// 状态变量
const loading = ref(false);
const reviews = ref<ReviewItem[]>([]);
const hotelId = ref<string>(''); // 移除默认值

// 统计信息
const reviewStats = reactive<ReviewStats>({
  totalReviews: 0,
  averageRating: 0,
  ratingDistribution: {
    "5": 0,
    "4": 0,
    "3": 0,
    "2": 0,
    "1": 0
  }
});

// 筛选条件
const filterRating = ref<number | null>(null);
const filterStatus = ref<string | null>(null);
const dateRange = ref<any[] | null>(null);

// 回复模态框
const replyModalVisible = ref(false);
const currentReview = ref<ReviewItem | null>(null);
const replyContent = ref('');

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 5,
  total: 0,
  onChange: (page: number) => {
    pagination.current = page;
    loadReviews();
  }
});

// 计算属性
const replyRate = computed(() => {
  const repliedCount = reviews.value.filter(review => review.reply).length;
  return reviews.value.length ? (repliedCount / reviews.value.length) * 100 : 0;
});

const ratingColor = computed(() => {
  const rating = reviewStats.averageRating;
  if (rating >= 4.5) return '#52c41a'; // 绿色
  if (rating >= 4) return '#1890ff'; // 蓝色
  if (rating >= 3) return '#faad14'; // 黄色
  return '#f5222d'; // 红色
});

// 方法
// 获取评分的颜色
function getRatingColor(rating: number): string {
  if (rating >= 5) return '#52c41a'; // 绿色
  if (rating >= 4) return '#1890ff'; // 蓝色
  if (rating >= 3) return '#faad14'; // 黄色
  if (rating >= 2) return '#fa8c16'; // 橙色
  return '#f5222d'; // 红色
}

// 获取特定评分的百分比
function getRatingDistributionPercent(rating: number): number {
  const count = reviewStats.ratingDistribution[rating] || 0;
  return reviewStats.totalReviews ? (count / reviewStats.totalReviews) * 100 : 0;
}

// 获取特定评分的评论数量
function getRatingCount(rating: number): number {
  return reviewStats.ratingDistribution[rating] || 0;
}

// 加载酒店评论列表
async function loadReviews() {
  try {
    loading.value = true;
    
    // 确保有hotelId
    if (!hotelStore.safeHotelId) {
      message.warning('未获取到酒店ID，无法加载评论数据');
      return;
    }
    
    // 准备查询参数
    const params: any = {
      page: pagination.current,
      pageSize: pagination.pageSize
    };
    
    // 添加筛选条件
    if (filterRating.value) {
      params.rating = filterRating.value;
    }
    
    if (filterStatus.value) {
      params.status = filterStatus.value;
    }
    
    if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
      params.startDate = dayjs(dateRange.value[0]).format('YYYY-MM-DD');
      params.endDate = dayjs(dateRange.value[1]).format('YYYY-MM-DD');
    }
    
    const response: any = await apiGetHotelReviews(hotelStore.safeHotelId, params);
    
    if (response.code === 200) {
      reviews.value = response.data.records;
      pagination.total = response.data.total;
    } else {
      message.error(response.msg || '获取评论列表失败');
    }
  } catch (error) {
    console.error('加载评论失败:', error);
    message.error('获取评论列表失败');
  } finally {
    loading.value = false;
  }
}

// 加载评论统计信息
async function loadReviewStats() {
  try {
    // 确保有hotelId
    if (!hotelStore.safeHotelId) {
      return;
    }
    
    const response: any = await apiGetHotelReviewStats(hotelStore.safeHotelId);
    
    if (response.code === 200) {
      reviewStats.totalReviews = response.data.totalReviews || 0;
      reviewStats.averageRating = response.data.averageRating || 0;
      reviewStats.ratingDistribution = response.data.ratingDistribution || {
        "5": 0,
        "4": 0,
        "3": 0,
        "2": 0,
        "1": 0
      };
    } else {
      message.error(response.msg || '获取评论统计信息失败');
    }
  } catch (error) {
    console.error('加载评论统计信息失败:', error);
    message.error('获取评论统计信息失败');
  }
}

// 应用筛选
function applyFilter() {
  pagination.current = 1;
  loadReviews();
  message.success('筛选已应用');
}

// 重置筛选
function resetFilter() {
  filterRating.value = null;
  filterStatus.value = null;
  dateRange.value = null;
  pagination.current = 1;
  loadReviews();
  message.success('筛选已重置');
}

// 打开回复模态框
function openReplyModal(review: ReviewItem) {
  currentReview.value = review;
  replyContent.value = review.reply || '';
  replyModalVisible.value = true;
}

// 提交回复
async function submitReply() {
  if (!replyContent.value.trim()) {
    message.error('回复内容不能为空');
    return;
  }
  
  if (!currentReview.value) {
    message.error('未选择评论');
    return;
  }
  
  try {
    const response: any = await apiReplyReview(
      currentReview.value.id.toString(), 
      replyContent.value
    );
    
    if (response.code === 200) {
      message.success('回复成功');
      replyModalVisible.value = false;
      
      // 更新本地数据
      const index = reviews.value.findIndex(r => r.id === currentReview.value!.id);
      if (index !== -1) {
        reviews.value[index].reply = replyContent.value;
        reviews.value[index].replyDate = dayjs().format('YYYY-MM-DD');
        reviews.value[index].status = 'replied';
      }
      
      // 重新加载数据
      loadReviews();
      loadReviewStats();
    } else {
      message.error(response.msg || '回复失败');
    }
  } catch (error) {
    console.error('回复评论失败:', error);
    message.error('回复评论失败');
  }
}

// 获取随机头像
function getRandomAvatar(id: number): string {
  const seed = id.toString();
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${seed}`;
}

// 初始化
onMounted(async () => {
  try {
    // 先确保hotelStore已初始化
    if (!hotelStore.isInitialized) {
      await hotelStore.getHotelInfo();
    }
    
    // 使用safeHotelId
    if (hotelStore.safeHotelId) {
      hotelId.value = hotelStore.safeHotelId;
      console.log('获取到酒店ID:', hotelId.value);
      
      // 加载数据
      loadReviews();
      loadReviewStats();
    } else {
      message.warning('未找到酒店ID，无法加载评论信息');
      console.error('酒店ID未找到');
    }
  } catch (error) {
    console.error('初始化评论管理页面失败:', error);
    message.error('加载失败，请刷新页面重试');
  }
});
</script>

<style scoped>
.filter-bar {
  margin-bottom: 16px;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.review-user {
  display: flex;
  align-items: center;
}

.user-name {
  margin-left: 8px;
  font-weight: 500;
}

.review-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.review-date {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.review-content {
  margin: 16px 0;
}

.review-text {
  margin-bottom: 16px;
}

.review-tags {
  margin-top: 12px;
}

.review-reply-section {
  margin-top: 20px;
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 8px;
  position: relative;
}

.reply-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.reply-title {
  margin: 0 8px;
  font-weight: 500;
}

.reply-date {
  font-size: 12px;
  color: #999;
}

.reply-content {
  color: #333;
  line-height: 1.6;
  margin-bottom: 8px;
}

.reply-actions {
  text-align: right;
  margin-top: 8px;
  border-top: 1px dashed #e8e8e8;
  padding-top: 8px;
}

.review-actions {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.review-preview {
  background-color: #f5f5f5;
  padding: 12px;
  border-radius: 8px;
}

.review-preview-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.stats-container {
  padding: 16px 0;
}

.stats-overview {
  display: flex;
  justify-content: space-around;
  margin-bottom: 24px;
}

.stat-item {
  text-align: center;
  width: 120px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
}

.stat-label {
  margin: 8px 0;
  color: #666;
}

.rating-distribution {
  padding: 0 16px;
}

.distribution-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}

.distribution-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.distribution-label {
  width: 40px;
}

.distribution-count {
  width: 40px;
  text-align: right;
}

.review-hidden {
  opacity: 0.6;
}
</style> 